import Router from "koa-router";
import serviceField from "../../service/field/index.js";
import response from "../../response.js";
import _ from "lodash";
const router = new Router();
router.post("/", async (ctx) => {
  try {
    const data = ctx.data;
    const result = await serviceField.save([
      data?.name,
      data?.type,
      data?.label,
    ]);
    if (!result) {
      ctx.body = response.fail({ msg: "新增失败" });
    } else {
      ctx.body = response.success({ msg: "新增成功" });
    }
  } catch (e) {
    console.error(e);
    ctx.body = response.fail({ msg: "新增失败" });
  }
});

router.get("/list", async (ctx) => {
  const list = await serviceField.getList();
  ctx.body = response.success({ data: { list: list } });
});
router.put("/", async (ctx) => {
  const data = ctx.data;
  if (_.isNil(data?.id)) {
    ctx.body = response.fail({ msg: "id not empty" });
    return;
  }

  const result = await serviceField.update([
    {
      fieldId: data?.id,
      name: data?.name,
      type: data?.type,
      label: data?.label,
    },
  ]);
  if (!result) {
    ctx.body = response.fail({ msg: "fail" });
  } else {
    ctx.body = response.success({ msg: "success" });
  }
});
router.delete("/:id", async (ctx) => {
  const { id } = ctx.params || {};
  if (!id && id !== 0) {
    ctx.body = response.fail({ msg: "id不能为空" });
    return;
  }
  const has = await serviceField.findById(id);

  if (!has?.length) {
    ctx.body = response.fail({ msg: "数据不存在" });
    return;
  }
  const result = await serviceField.del(id);
  if (result) {
    ctx.body = response.success({ msg: "删除成功" });
  } else {
    ctx.body = response.fail({ msg: "删除失败" });
  }
});
export default router;
